package com.project.mvprxsample.net;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;

import com.project.mvprxsample.app.MyApplication;
import com.project.mvprxsample.utils.MD5;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttp3Utils {
    private Context mContext;
    private OkHttpClient mOkHttpClient;

    private static final long TIME_OUT = 30;

    public OkHttp3Utils(Context mContext) {
        this.mContext = mContext;
    }

    /**
     * 获取OkHttpClient对象
     *
     * @return
     */
    public OkHttpClient getOkHttpClient() {
        if (null == mOkHttpClient) {
            File cacheDirectory = new File(mContext.getApplicationContext().getCacheDir().getAbsolutePath(), "MyCache");
            Cache cache = new Cache(cacheDirectory, 10 * 1024 * 1024);
            //同样okhttp3后也使用build设计模式
            mOkHttpClient = new OkHttpClient.Builder()
                    //设置一个自动管理cookies的管理器
                   // .cookieJar(new CookiesManager())
                    //添加拦截器
                    .addInterceptor(new MyInterceptor(mContext))
                    //添加网络连接器
                    //.addNetworkInterceptor(new CookiesInterceptor(MyApplication.getInstance().getApplicationContext()))
                    //设置请求读写的超时时间
                    .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                    .writeTimeout(TIME_OUT, TimeUnit.SECONDS)
                    .readTimeout(TIME_OUT, TimeUnit.SECONDS)
                    .cache(cache)
                    .build();
        }
        return mOkHttpClient;
    }

    /**
     * 拦截器
     */
    private class MyInterceptor implements Interceptor {
        private Context mContext;

        public MyInterceptor(Context mContext) {
            this.mContext = mContext;
        }

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request oldRequest = chain.request();
            //ysl-----start----------------以下代码为添加一些公共参数使用--------------------------
            // 添加新的参数
            String time = System.currentTimeMillis()/1000 + "";
            String mKey = "f6f712249f4b725fac309504d633f839";
            HttpUrl.Builder authorizedUrlBuilder = oldRequest.url()
                    .newBuilder()
                    .scheme(oldRequest.url().scheme())
                    .host(oldRequest.url().host())
                    .addQueryParameter("os", "android")
                    .addQueryParameter("time", URLEncoder.encode(time, "UTF-8"))
                    .addQueryParameter("version", "1.1.0")
                    .addQueryParameter("sign", MD5.md5("key=" + mKey));
            // 构建新的请求
            Request newRequest = oldRequest.newBuilder()
                    .method(oldRequest.method(), oldRequest.body())
                    .url(authorizedUrlBuilder.build())
                    .build();
            //ysl-----end
            if (!isNetworkReachable(mContext.getApplicationContext())) {
                Toast.makeText(mContext.getApplicationContext(), "暂无网络", Toast.LENGTH_SHORT).show();
                newRequest = newRequest.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)//无网络时只从缓存中读取
                        .build();
            }

            Response response = chain.proceed(newRequest);
            if (isNetworkReachable(mContext.getApplicationContext())) {
                int maxAge = 60 * 60; // 有网络时 设置缓存超时时间1个小时
                response.newBuilder()
                        .removeHeader("Pragma")
                        .header("Cache-Control", "public, max-age=" + maxAge)
                        .build();
            } else {
                int maxStale = 60 * 60 * 24 * 28; // 无网络时，设置超时为4周
                response.newBuilder()
                        .removeHeader("Pragma")
                        .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                        .build();
            }
            //***************打印Log*****************************
            String requestUrl = newRequest.url().toString(); // 获取请求url地址
            String methodStr = newRequest.method(); // 获取请求方式
            RequestBody body = newRequest.body(); // 获取请求body
            String bodyStr = (body == null ? "" : body.toString());
            // 打印Request数据
            Log.i("ysl", "requestUrl=====>" + requestUrl);
            Log.i("ysl", "requestMethod=====>" + methodStr);
            Log.i("ysl", "requestBody=====>" + body);
            return response;
        }
    }

    /**
     * 判断网络是否可用
     *
     * @param context Context对象
     */
    public Boolean isNetworkReachable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo current = cm.getActiveNetworkInfo();
        if (current == null) {
            return false;
        }
        return (current.isAvailable());
    }
}
